import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { ArticleLabel } from 'src/entities/article_label.entity';
import { Repository } from 'typeorm';

@Injectable()
export class ArticleLabelService {
  constructor(
    @InjectRepository(ArticleLabel)
    private articleLabelRepository: Repository<ArticleLabel>,
  ) {}

  async findAll(findOption={}): Promise<ArticleLabel[]> {
    const articles=await this.articleLabelRepository.find(findOption);
    return articles;
  }

  async findOne(id: number): Promise<ArticleLabel> {
    return await this.articleLabelRepository.findOne(id);
  }

  async removeOne(id: number): Promise<ArticleLabel> {
    const old=await this.findOne(id);
    const res=await this.articleLabelRepository.delete(id);
    return res.affected===1?old:null;
  }

  async addOne(article_label: ArticleLabel): Promise<ArticleLabel> {
    const u=Object.assign(new ArticleLabel(),article_label);
    const res=await this.articleLabelRepository.insert(u);
    return this.findOne(res.identifiers[0].id);
  }

  async modifyOne(id: number,article_label: ArticleLabel): Promise<ArticleLabel> {
    const u=Object.assign(new ArticleLabel(),article_label);
    const res=await this.articleLabelRepository.update(id,u);
    return await this.findOne(id);
  }

  async count(option={}): Promise<number> {
    return await this.articleLabelRepository.count(option);
  }

  async getPagination(page={},sort={},where={}){
    const p=Object.assign({
      size:10,
      current:0,
      total:0,
    },page);
    const ars=await this.findAll({
      order:sort,
      take:p.size,
      skip:p.current,
      where:where
    });
    const total = await this.count(where);
    p.total=total;
    return {
      page:p,
      article_labels:ars,
    }
  }
}
